package com.jckl.foodathon.sqlite.dao;

import java.util.List;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.SqlUtils;
import de.greenrobot.dao.internal.DaoConfig;
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

import com.jckl.foodathon.sqlite.model.TB_Blogger;
import com.jckl.foodathon.sqlite.model.TB_Store;

import com.jckl.foodathon.sqlite.model.TB_Blog;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/** 
 * DAO for table TB__BLOG.
*/
public class TB_BlogDao extends AbstractDao<TB_Blog, Long> {

    public static final String TABLENAME = "TB__BLOG";

    /**
     * Properties of entity TB_Blog.<br/>
     * Can be used for QueryBuilder and for referencing column names.
    */
    public static class Properties {
        public final static Property Id = new Property(0, Long.class, "id", true, "_id");
        public final static Property Title = new Property(1, String.class, "title", false, "TITLE");
        public final static Property BlogURL = new Property(2, String.class, "blogURL", false, "BLOG_URL");
        public final static Property PostDate = new Property(3, java.util.Date.class, "postDate", false, "POST_DATE");
        public final static Property BloggerId = new Property(4, Long.class, "bloggerId", false, "BLOGGER_ID");
        public final static Property StoreId = new Property(5, Long.class, "storeId", false, "STORE_ID");
    };

    private DaoSession daoSession;

    private Query<TB_Blog> tB_Blogger_BlogsQuery;
    private Query<TB_Blog> tB_Store_BlogsQuery;

    public TB_BlogDao(DaoConfig config) {
        super(config);
    }
    
    public TB_BlogDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
        this.daoSession = daoSession;
    }

    /** Creates the underlying database table. */
    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "'TB__BLOG' (" + //
                "'_id' INTEGER PRIMARY KEY ," + // 0: id
                "'TITLE' TEXT," + // 1: title
                "'BLOG_URL' TEXT," + // 2: blogURL
                "'POST_DATE' INTEGER," + // 3: postDate
                "'BLOGGER_ID' INTEGER," + // 4: bloggerId
                "'STORE_ID' INTEGER);"); // 5: storeId
    }

    /** Drops the underlying database table. */
    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'TB__BLOG'";
        db.execSQL(sql);
    }

    /** @inheritdoc */
    @Override
    protected void bindValues(SQLiteStatement stmt, TB_Blog entity) {
        stmt.clearBindings();
 
        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }
 
        String title = entity.getTitle();
        if (title != null) {
            stmt.bindString(2, title);
        }
 
        String blogURL = entity.getBlogURL();
        if (blogURL != null) {
            stmt.bindString(3, blogURL);
        }
 
        java.util.Date postDate = entity.getPostDate();
        if (postDate != null) {
            stmt.bindLong(4, postDate.getTime());
        }
 
        Long bloggerId = entity.getBloggerId();
        if (bloggerId != null) {
            stmt.bindLong(5, bloggerId);
        }
 
        Long storeId = entity.getStoreId();
        if (storeId != null) {
            stmt.bindLong(6, storeId);
        }
    }

    @Override
    protected void attachEntity(TB_Blog entity) {
        super.attachEntity(entity);
        entity.__setDaoSession(daoSession);
    }

    /** @inheritdoc */
    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
    }    

    /** @inheritdoc */
    @Override
    public TB_Blog readEntity(Cursor cursor, int offset) {
        TB_Blog entity = new TB_Blog( //
            cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
            cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // title
            cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // blogURL
            cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)), // postDate
            cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4), // bloggerId
            cursor.isNull(offset + 5) ? null : cursor.getLong(offset + 5) // storeId
        );
        return entity;
    }
     
    /** @inheritdoc */
    @Override
    public void readEntity(Cursor cursor, TB_Blog entity, int offset) {
        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
        entity.setTitle(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
        entity.setBlogURL(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
        entity.setPostDate(cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)));
        entity.setBloggerId(cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4));
        entity.setStoreId(cursor.isNull(offset + 5) ? null : cursor.getLong(offset + 5));
     }
    
    /** @inheritdoc */
    @Override
    protected Long updateKeyAfterInsert(TB_Blog entity, long rowId) {
        entity.setId(rowId);
        return rowId;
    }
    
    /** @inheritdoc */
    @Override
    public Long getKey(TB_Blog entity) {
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    /** @inheritdoc */
    @Override    
    protected boolean isEntityUpdateable() {
        return true;
    }
    
    /** Internal query to resolve the "blogs" to-many relationship of TB_Blogger. */
    public List<TB_Blog> _queryTB_Blogger_Blogs(Long bloggerId) {
        synchronized (this) {
            if (tB_Blogger_BlogsQuery == null) {
                QueryBuilder<TB_Blog> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.BloggerId.eq(null));
                tB_Blogger_BlogsQuery = queryBuilder.build();
            }
        }
        Query<TB_Blog> query = tB_Blogger_BlogsQuery.forCurrentThread();
        query.setParameter(0, bloggerId);
        return query.list();
    }

    /** Internal query to resolve the "blogs" to-many relationship of TB_Store. */
    public List<TB_Blog> _queryTB_Store_Blogs(Long storeId) {
        synchronized (this) {
            if (tB_Store_BlogsQuery == null) {
                QueryBuilder<TB_Blog> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.StoreId.eq(null));
                tB_Store_BlogsQuery = queryBuilder.build();
            }
        }
        Query<TB_Blog> query = tB_Store_BlogsQuery.forCurrentThread();
        query.setParameter(0, storeId);
        return query.list();
    }

    private String selectDeep;

    protected String getSelectDeep() {
        if (selectDeep == null) {
            StringBuilder builder = new StringBuilder("SELECT ");
            SqlUtils.appendColumns(builder, "T", getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T0", daoSession.getTB_BloggerDao().getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T1", daoSession.getTB_StoreDao().getAllColumns());
            builder.append(" FROM TB__BLOG T");
            builder.append(" LEFT JOIN TB__BLOGGER T0 ON T.'BLOGGER_ID'=T0.'_id'");
            builder.append(" LEFT JOIN TB__STORE T1 ON T.'STORE_ID'=T1.'_id'");
            builder.append(' ');
            selectDeep = builder.toString();
        }
        return selectDeep;
    }
    
    protected TB_Blog loadCurrentDeep(Cursor cursor, boolean lock) {
        TB_Blog entity = loadCurrent(cursor, 0, lock);
        int offset = getAllColumns().length;

        TB_Blogger tB_Blogger = loadCurrentOther(daoSession.getTB_BloggerDao(), cursor, offset);
        entity.setTB_Blogger(tB_Blogger);
        offset += daoSession.getTB_BloggerDao().getAllColumns().length;

        TB_Store tB_Store = loadCurrentOther(daoSession.getTB_StoreDao(), cursor, offset);
        entity.setTB_Store(tB_Store);

        return entity;    
    }

    public TB_Blog loadDeep(Long key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder(getSelectDeep());
        builder.append("WHERE ");
        SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
        String sql = builder.toString();
        
        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);
        
        try {
            boolean available = cursor.moveToFirst();
            if (!available) {
                return null;
            } else if (!cursor.isLast()) {
                throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
            }
            return loadCurrentDeep(cursor, true);
        } finally {
            cursor.close();
        }
    }
    
    /** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
    public List<TB_Blog> loadAllDeepFromCursor(Cursor cursor) {
        int count = cursor.getCount();
        List<TB_Blog> list = new ArrayList<TB_Blog>(count);
        
        if (cursor.moveToFirst()) {
            if (identityScope != null) {
                identityScope.lock();
                identityScope.reserveRoom(count);
            }
            try {
                do {
                    list.add(loadCurrentDeep(cursor, false));
                } while (cursor.moveToNext());
            } finally {
                if (identityScope != null) {
                    identityScope.unlock();
                }
            }
        }
        return list;
    }
    
    protected List<TB_Blog> loadDeepAllAndCloseCursor(Cursor cursor) {
        try {
            return loadAllDeepFromCursor(cursor);
        } finally {
            cursor.close();
        }
    }
    

    /** A raw-style query where you can pass any WHERE clause and arguments. */
    public List<TB_Blog> queryDeep(String where, String... selectionArg) {
        Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
        return loadDeepAllAndCloseCursor(cursor);
    }
 
}
